package org.s3.project.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.s3.project.entity.ShoppingCart;
import org.s3.project.entity.shopingzailaiyidan;
import org.s3.project.mapper.ShoppingCartMapper;
import org.s3.project.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cfx
 * @version 1.0
 * @Description
 * @date 2025/2/9 10:28
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    //修改购物车里面的数量
    @Override
    public Boolean updateShoppingCart(Integer number, Integer user_id, Integer id) {
        return shoppingCartMapper.updateShoppingCart(number, user_id, id);
    }
  //批量删除
    @Override
    public Boolean deleteShopings(List<String> ids) {
        return shoppingCartMapper.deleteShopings(ids);
    }
    //查询购物车是否有这个商品
    @Override
    public int selectSole(Integer user_id, Integer dish_id) {
        return shoppingCartMapper.selectSole(user_id, dish_id);
    }
  //有这个商品直接+1
    @Override
    public Boolean updateAddShoping(Integer user_id, Integer dish_id) {
        return shoppingCartMapper.updateAddShoping(user_id,dish_id);
    }
    public String addlistShopingCart(List<ShoppingCart> shoppingCartList) {
        List<shopingzailaiyidan> toUpdate = new ArrayList<>(); // 收集需要更新的商品
        boolean isAnyFailed = false; // 标记是否有操作失败
        for (ShoppingCart cart : shoppingCartList) {
            boolean exists = selectShoppingCart(cart.getUser_id(), cart.getDish_id());
            if (exists) {
                // 收集需要更新的商品
                toUpdate.add(new shopingzailaiyidan(
                        cart.getUser_id(),
                        cart.getDish_id(),
                        cart.getNumber()
                ));
            } else {
                // 新增商品
                if (!shoppingCartMapper.addShoppingCart(shoppingCartList)) {
                    isAnyFailed = true;
                }
            }
        }
        // 批量更新需要更新的商品
        if (!toUpdate.isEmpty()) {
            if (!shoppingCartMapper.updateShoppingCart(toUpdate)) {
                isAnyFailed = true;
            }
        }
        return isAnyFailed ? "失败" : "成功";
    }


    //查询
    @Override
    public Boolean selectShoppingCart(long userId, long dishId) {
        Boolean result = shoppingCartMapper.selectShoppingCart(userId, dishId);
        return result != null ? result : false;
    }

    //修改
    @Override
    public Boolean updateShoppingCart(List<shopingzailaiyidan> shoppingCartList) {
        return shoppingCartMapper.updateShoppingCart(shoppingCartList);
    }


}
